#!/usr/bin/env python3
"""
阶段2：智能语义分析与角色标注
基于转录结果进行需求提取、角色识别、优先级分析
输出：semantic_analysis.json/.md + PRD文档
"""

import json
import re
import sys
from pathlib import Path
from typing import Dict, List, Optional
from datetime import datetime
from collections import defaultdict
import logging
import requests

from ..core.config import settings

logger = logging.getLogger(__name__)

class Stage2SemanticAnalyzer:
    """智能语义分析器"""
    
    def __init__(self, stage1_data: Dict, output_dir: Path, mode: str = "auto"):
        self.stage1_data = stage1_data
        self.output_dir = Path(output_dir)
        self.output_dir.mkdir(parents=True, exist_ok=True)
        self.mode = mode  # auto, interactive, rules
        
        # DeepSeek API配置
        self.api_key = settings.DEEPSEEK_API_KEY
        self.base_url = settings.DEEPSEEK_BASE_URL
        self.model = settings.DEEPSEEK_MODEL
        self.use_ai = bool(self.api_key)
        
        # 角色识别关键词
        self.role_keywords = {
            "需求方（客户）": ["要求", "希望", "想要", "我们公司", "我们这边", "预算", "成本", "付费", "投资"],
            "需求方（业务人员）": ["业务", "流程", "用户", "客户", "市场", "运营", "销售"],
            "乙方（技术）": ["技术", "架构", "开发", "测试", "部署", "接口", "代码", "实现", "数据库"],
            "乙方（产品）": ["产品", "功能", "需求", "用户体验", "设计", "交互", "界面"],
            "乙方（项目经理）": ["项目", "进度", "时间", "计划", "排期", "里程碑", "交付", "资源"],
            "其他": []
        }
        
        # 需求类型模式
        self.requirement_patterns = {
            "功能需求": {
                "keywords": ["功能", "模块", "页面", "按钮", "操作", "流程", "实现", "支持"],
                "patterns": [r"需要.*?功能", r"实现.*?功能", r"支持.*?操作", r"添加.*?模块"]
            },
            "性能需求": {
                "keywords": ["性能", "速度", "响应", "并发", "延迟", "吞吐量", "优化"],
                "patterns": [r"响应时间", r"性能.*?要求", r"速度.*?快", r".*?秒内"]
            },
            "安全需求": {
                "keywords": ["安全", "权限", "认证", "加密", "登录", "授权", "防护"],
                "patterns": [r"权限.*?控制", r"安全.*?要求", r"需要.*?认证", r"防止.*?攻击"]
            },
            "界面需求": {
                "keywords": ["界面", "UI", "页面", "显示", "布局", "样式", "美观"],
                "patterns": [r"界面.*?设计", r"页面.*?展示", r"UI.*?要求"]
            },
            "数据需求": {
                "keywords": ["数据", "存储", "数据库", "备份", "导入", "导出", "统计"],
                "patterns": [r"数据.*?存储", r"导入.*?数据", r"统计.*?信息"]
            }
        }
        
        # 优先级规则
        self.priority_rules = {
            "P0": ["紧急", "立即", "马上", "必须", "一定要", "关键", "重要"],
            "P1": ["重要", "优先", "尽快", "应该", "需要", "希望"],
            "P2": ["最好", "建议", "可以", "考虑", "如果可能"],
            "P3": ["如果", "可能", "或许", "将来", "后续", "以后"]
        }
    
    def _call_deepseek_api(self, prompt: str, max_tokens: int = 2000) -> str:
        """调用DeepSeek API"""
        if not self.use_ai:
            return ""
            
        try:
            headers = {
                "Authorization": f"Bearer {self.api_key}",
                "Content-Type": "application/json"
            }
            
            data = {
                "model": self.model,
                "messages": [
                    {"role": "user", "content": prompt}
                ],
                "max_tokens": max_tokens,
                "temperature": 0.3
            }
            
            response = requests.post(
                f"{self.base_url}chat/completions",
                headers=headers,
                json=data,
                timeout=120  # 增加到120秒
            )
            
            if response.status_code == 200:
                result = response.json()
                return result["choices"][0]["message"]["content"]
            else:
                logger.error(f"DeepSeek API调用失败: {response.status_code} - {response.text}")
                return ""
                
        except Exception as e:
            logger.error(f"DeepSeek API调用异常: {e}")
            return ""
    
    def process(self) -> Dict:
        """执行智能语义分析"""
        logger.info("阶段2：开始智能语义分析")
        
        segments = self.stage1_data["data"]["segments"]
        
        # 1. 说话人角色识别
        if self.mode == "interactive":
            role_mapping = self._interactive_role_assignment(segments)
        else:
            role_mapping = self._identify_speaker_roles(segments)
        
        # 2. 需求提取
        requirements = self._extract_requirements(segments, role_mapping)
        
        # 3. 冲突检测
        conflicts = self._detect_requirement_conflicts(requirements)
        
        # 4. 生成分析报告
        analysis_summary = self._generate_analysis_summary(requirements, role_mapping)
        
        result_data = {
            "source_file": self.stage1_data.get("stage1_file", ""),
            "analysis_timestamp": datetime.now().isoformat(),
            "processing_mode": self.mode,
            "speaker_roles": role_mapping,
            "total_requirements": len(requirements),
            "requirements": requirements,
            "requirement_conflicts": conflicts,
            "analysis_summary": analysis_summary
        }
        
        # 保存JSON结果
        output_file = self.output_dir / "stage2" / "semantic_analysis.json"
        output_file.parent.mkdir(parents=True, exist_ok=True)
        
        with open(output_file, 'w', encoding='utf-8') as f:
            json.dump(result_data, f, ensure_ascii=False, indent=2)
        
        # 保存可读格式
        readable_file = output_file.with_suffix('.md')
        self._save_readable_analysis(result_data, readable_file)
        
        # 生成PRD文档
        prd_file = self._generate_prd(result_data)
        
        # 生成会议纪要
        meeting_notes_file = self._generate_meeting_notes(result_data)
        
        result = {
            "stage2_file": str(output_file),
            "prd_file": str(prd_file),
            "meeting_notes_file": str(meeting_notes_file),
            "data": result_data
        }
        
        logger.info(f"阶段2完成：{output_file}")
        return result
    
    def _interactive_role_assignment(self, segments: List[Dict]) -> Dict[str, str]:
        """交互式角色分配"""
        speakers = set(segment["speaker"] for segment in segments)
        
        print("\n" + "="*50)
        print("阶段2：说话人角色标注")
        print("="*50)
        
        role_mapping = {}
        role_options = {
            "1": "需求方（客户）",
            "2": "需求方（业务人员）", 
            "3": "乙方（技术）",
            "4": "乙方（产品）",
            "5": "乙方（项目经理）",
            "6": "其他"
        }
        
        for speaker in sorted(speakers):
            print(f"\n请为 {speaker} 选择角色：")
            for key, value in role_options.items():
                print(f"  {key}. {value}")
            
            while True:
                choice = input(f"选择 {speaker} 的角色 (1-6): ").strip()
                if choice in role_options:
                    role_mapping[speaker] = role_options[choice]
                    break
                else:
                    print("请输入 1-6 之间的数字")
        
        return role_mapping
    
    def _identify_speaker_roles(self, segments: List[Dict]) -> Dict:
        """自动识别说话人角色"""
        speaker_scores = defaultdict(lambda: defaultdict(int))
        
        for segment in segments:
            speaker = segment["speaker"]
            text = segment["text"]
            
            # 统计各角色关键词出现次数
            for role, keywords in self.role_keywords.items():
                score = sum(1 for keyword in keywords if keyword in text)
                speaker_scores[speaker][role] += score
        
        # 为每个说话人分配最可能的角色
        role_mapping = {}
        for speaker, scores in speaker_scores.items():
            if scores:
                best_role = max(scores, key=scores.get)
                if scores[best_role] > 0:
                    role_mapping[speaker] = best_role
                else:
                    role_mapping[speaker] = "其他"
            else:
                role_mapping[speaker] = "其他"
        
        return role_mapping
    
    def _extract_requirements(self, segments: List[Dict], role_mapping: Dict) -> List[Dict]:
        """提取需求"""
        requirements = []
        
        for i, segment in enumerate(segments):
            text = segment["text"]
            speaker = segment["speaker"]
            role = role_mapping.get(speaker, "其他")
            
            # 检查是否包含需求信息
            if not self._contains_requirement(text):
                continue
            
            # 分句处理
            sentences = re.split(r'[。！？\n]', text)
            
            for sentence in sentences:
                sentence = sentence.strip()
                if not sentence or not self._contains_requirement(sentence):
                    continue
                
                req = {
                    "id": f"REQ_{len(requirements) + 1:03d}",
                    "requirement_text": sentence,
                    "original_text": text,
                    "speaker": speaker,
                    "speaker_role": role,
                    "timestamp": segment["timestamp"],
                    "requirement_type": self._classify_requirement_type(sentence),
                    "priority": self._determine_priority(sentence),
                    "confidence": self._calculate_confidence(sentence)
                }
                
                if req["confidence"] > 0.3:  # 过滤低置信度需求
                    requirements.append(req)
        
        return requirements
    
    def _contains_requirement(self, text: str) -> bool:
        """判断文本是否包含需求信息"""
        requirement_indicators = [
            "需要", "要求", "希望", "想要", "应该", "必须",
            "功能", "实现", "支持", "提供", "开发", "设计",
            "问题", "改进", "优化", "增加", "添加", "修改"
        ]
        
        return any(indicator in text for indicator in requirement_indicators)
    
    def _classify_requirement_type(self, text: str) -> str:
        """分类需求类型"""
        scores = {}
        
        for req_type, config in self.requirement_patterns.items():
            score = 0
            
            # 关键词匹配
            for keyword in config["keywords"]:
                if keyword in text:
                    score += 1
            
            # 模式匹配
            for pattern in config["patterns"]:
                if re.search(pattern, text):
                    score += 2
            
            scores[req_type] = score
        
        return max(scores, key=scores.get) if scores else "其他需求"
    
    def _determine_priority(self, text: str) -> str:
        """确定优先级"""
        for priority, keywords in self.priority_rules.items():
            if any(keyword in text for keyword in keywords):
                return priority
        return "P2"
    
    def _calculate_confidence(self, text: str) -> float:
        """计算置信度"""
        score = 0.0
        
        # 长度因子
        if len(text) > 10:
            score += 0.2
        
        # 需求词汇密度
        req_words = ["需要", "要求", "功能", "实现", "支持"]
        matches = sum(1 for word in req_words if word in text)
        score += matches * 0.2
        
        # 具体性（包含具体名词）
        if re.search(r'[A-Za-z]+|数据|系统|界面|功能', text):
            score += 0.3
        
        return min(score, 1.0)
    
    def _detect_requirement_conflicts(self, requirements: List[Dict]) -> List[Dict]:
        """检测需求冲突"""
        conflicts = []
        conflict_patterns = [
            ("快速", "质量"),
            ("成本", "功能"),
            ("简单", "强大"),
            ("安全", "易用"),
            ("性能", "成本")
        ]
        
        for i, req1 in enumerate(requirements):
            for j, req2 in enumerate(requirements[i+1:], i+1):
                text1 = req1["requirement_text"].lower()
                text2 = req2["requirement_text"].lower()
                
                for pattern1, pattern2 in conflict_patterns:
                    if pattern1 in text1 and pattern2 in text2:
                        conflicts.append({
                            "requirement1_id": req1["id"],
                            "requirement2_id": req2["id"],
                            "conflict_type": "目标冲突",
                            "description": f"'{pattern1}'与'{pattern2}'可能存在冲突"
                        })
        
        return conflicts
    
    def _generate_analysis_summary(self, requirements: List[Dict], role_mapping: Dict) -> Dict:
        """生成分析总结"""
        type_counts = defaultdict(int)
        priority_counts = defaultdict(int)
        role_counts = defaultdict(int)
        
        for req in requirements:
            type_counts[req["requirement_type"]] += 1
            priority_counts[req["priority"]] += 1
            role_counts[req["speaker_role"]] += 1
        
        return {
            "total_requirements": len(requirements),
            "requirements_by_type": dict(type_counts),
            "requirements_by_priority": dict(priority_counts),
            "requirements_by_role": dict(role_counts),
            "average_confidence": sum(req["confidence"] for req in requirements) / len(requirements) if requirements else 0,
            "identified_speakers": len(role_mapping),
            "role_distribution": role_mapping
        }
    
    def _save_readable_analysis(self, data: Dict, output_file: Path):
        """保存可读格式的需求分析"""
        with open(output_file, 'w', encoding='utf-8') as f:
            f.write("# 智能语义分析报告\n\n")
            f.write(f"**分析时间**: {data['analysis_timestamp']}\n")
            f.write(f"**源文件**: {data['source_file']}\n")
            f.write(f"**处理模式**: {data['processing_mode']}\n")
            f.write(f"**需求总数**: {data['total_requirements']}\n\n")
            
            # 说话人角色分布
            f.write("## 🎭 说话人角色识别\n\n")
            for speaker, role in data["speaker_roles"].items():
                f.write(f"- **{speaker}**: {role}\n")
            f.write("\n")
            
            # 需求总结
            summary = data["analysis_summary"]
            f.write("## 📊 需求分析概览\n\n")
            f.write("### 按类型分布\n")
            for req_type, count in summary["requirements_by_type"].items():
                f.write(f"- **{req_type}**: {count}个\n")
            
            f.write("\n### 按优先级分布\n")
            for priority, count in summary["requirements_by_priority"].items():
                f.write(f"- **{priority}**: {count}个\n")
            
            f.write(f"\n### 平均置信度: {summary['average_confidence']:.2f}\n\n")
            
            # 详细需求
            f.write("## 📋 需求详情\n\n")
            for req in data["requirements"]:
                f.write(f"### {req['id']}: {req['requirement_text']}\n")
                f.write(f"- **类型**: {req['requirement_type']}\n")
                f.write(f"- **优先级**: {req['priority']}\n")
                f.write(f"- **提出方**: {req['speaker_role']} ({req['speaker']})\n")
                f.write(f"- **置信度**: {req['confidence']:.2f}\n")
                f.write(f"- **时间戳**: {req['timestamp']}\n\n")
            
            # 冲突分析
            if data["requirement_conflicts"]:
                f.write("## ⚠️ 需求冲突检测\n\n")
                for conflict in data["requirement_conflicts"]:
                    f.write(f"- **{conflict['requirement1_id']} vs {conflict['requirement2_id']}**\n")
                    f.write(f"  - 冲突类型: {conflict['conflict_type']}\n")
                    f.write(f"  - 描述: {conflict['description']}\n\n")
            
            f.write("\n---\n\n")
            f.write("**说明**: 本报告由AI自动生成，建议人工确认重要需求\n")
    
    def _generate_prd(self, analysis_data: Dict) -> Path:
        """生成PRD文档"""
        requirements = analysis_data["requirements"]
        
        prd_file = self.output_dir / "stage2" / "PRD文档.md"
        prd_file.parent.mkdir(parents=True, exist_ok=True)
        
        # 如果启用AI，使用DeepSeek生成更智能的PRD
        if self.use_ai and requirements:
            ai_prd_content = self._generate_ai_prd(analysis_data)
            if ai_prd_content:
                with open(prd_file, 'w', encoding='utf-8') as f:
                    f.write(ai_prd_content)
                return prd_file
            else:
                # AI生成失败，抛出异常而不是使用规则引擎
                raise Exception("DeepSeek AI PRD生成失败，请检查API配置或网络连接")
        
        # 如果没有启用AI，直接抛出异常
        raise Exception("AI功能未启用，无法生成PRD文档")
    
    def _generate_ai_prd(self, analysis_data: Dict) -> str:
        """使用DeepSeek AI生成智能PRD文档"""
        requirements = analysis_data["requirements"]
        summary = analysis_data["analysis_summary"]
        
        # 构建需求信息
        req_text = ""
        for req in requirements[:20]:  # 限制最多20个需求避免prompt过长
            req_text += f"- {req['requirement_text']} (优先级: {req['priority']}, 类型: {req['requirement_type']}, 提出方: {req['speaker_role']})\n"
        
        # 构建参与方信息
        participants = ""
        for speaker, role in summary["role_distribution"].items():
            participants += f"- {speaker}: {role}\n"
        
        prompt = f"""请基于以下会议信息生成一份专业的产品需求文档(PRD)，要求格式清晰、内容详实：

## 会议参与方
{participants}

## 识别到的需求列表（显示前20项）
{req_text}

## 需求统计
- 总需求数: {summary['total_requirements']}个
- 需求类型分布: {', '.join([f'{k}({v}个)' for k, v in summary['requirements_by_type'].items()])}
- 优先级分布: {', '.join([f'{k}({v}个)' for k, v in summary['requirements_by_priority'].items()])}

请生成一份包含以下结构的PRD文档：
1. 项目概述
2. 需求分析与优先级
3. 功能规格详细描述  
4. 技术架构建议
5. 验收标准
6. 风险评估与缓解方案
7. 项目时间线建议

要求：
- 使用Markdown格式
- 内容要专业、具体、可执行
- 合理推理和补充技术细节
- 提供可行的实施建议
- 识别潜在风险并给出解决方案
- 字数控制在3000字以内

请直接返回完整的PRD文档内容："""

        logger.info(f"正在使用DeepSeek AI生成PRD文档...（Prompt长度: {len(prompt)}字符）")
        ai_response = self._call_deepseek_api(prompt, max_tokens=4000)
        
        if ai_response:
            # 在文档末尾添加生成信息
            ai_response += f"\n\n---\n\n**文档生成信息**:\n"
            ai_response += f"- 生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n"
            ai_response += f"- 生成模型: {self.model}\n"
            ai_response += f"- 基于需求数: {summary['total_requirements']}个\n"
            ai_response += f"- 处理模式: AI增强分析\n"
            logger.info("DeepSeek AI PRD文档生成完成")
            return ai_response
        else:
            logger.error("DeepSeek AI PRD文档生成失败")
            return ""
    
    def _generate_meeting_notes(self, analysis_data: Dict) -> Path:
        """生成会议纪要"""
        notes_file = self.output_dir / "stage2" / "会议纪要.md"
        notes_file.parent.mkdir(parents=True, exist_ok=True)
        
        with open(notes_file, 'w', encoding='utf-8') as f:
            f.write("# 会议纪要\n\n")
            f.write(f"**会议时间**: {analysis_data['analysis_timestamp'][:10]}\n")
            f.write(f"**会议主题**: 产品需求讨论\n")
            f.write(f"**参会人员**: {len(analysis_data['speaker_roles'])}人\n")
            f.write(f"**处理模式**: {analysis_data.get('processing_mode', 'auto')}\n\n")
            
            # 参会人员
            f.write("## 参会人员\n\n")
            for speaker, role in analysis_data["speaker_roles"].items():
                f.write(f"- **{speaker}** ({role})\n")
            f.write("\n")
            
            # 会议要点
            f.write("## 会议要点\n\n")
            summary = analysis_data["analysis_summary"]
            f.write(f"1. 共讨论了 **{summary['total_requirements']}** 个需求点\n")
            f.write(f"2. 平均需求置信度: **{summary['average_confidence']:.2f}**\n")
            f.write(f"3. 主要涉及: {', '.join(summary['requirements_by_type'].keys())}\n\n")
            
            # 关键决议
            f.write("## 关键决议\n\n")
            high_priority_reqs = [req for req in analysis_data["requirements"] if req["priority"] in ["P0", "P1"]]
            if high_priority_reqs:
                for req in high_priority_reqs:
                    f.write(f"- **{req['requirement_text']}** (优先级: {req['priority']})\n")
            else:
                f.write("- 待进一步确认优先级\n")
            f.write("\n")
            
            # 行动项
            f.write("## 后续行动\n\n")
            f.write("- [ ] 技术团队评估实现方案\n")
            f.write("- [ ] 产品团队细化需求文档\n")
            f.write("- [ ] 项目管理制定时间计划\n")
            f.write("- [ ] 安排下次评审会议\n\n")
            
            f.write("---\n\n")
            f.write("*本纪要由AI根据会议录音自动生成*\n")
        
        return notes_file